#!/bin/bash

# Script which performs cleanup of files in the runtime environment in
# preparation for bundling.  This performs various tasks such as removing
# unneeded files, stripping binaries, etc.
#
# The one thing it does not do is to run rebase; this needs to be done using a
# subcyg shell see the $(SAGE_ROOT_RUNTIME) target in the Makefile.
set -x

SAGE_ROOT_RUNTIME="$1"

cd "$SAGE_ROOT_RUNTIME"

# Clean up some files that are not needed at runtime
rm -rf bootstrap config.* logs upstream local/var/tmp/sage/build/* \
       local/var/lock/* build/pkgs/sagelib/src src/build \
       local/share/doc/sage/doctrees local/var/lib/sage/wheels .git*

# This shouldn't be necessary but it seems to help ensure that the main
# Makefile is newer than its prerequisites
touch "build/make/Makefile"

# Add src/.norebuild to prevent sagelib from getting rebuilt, since src/build
# has been removed; see https://trac.sagemath.org/ticket/29158
touch src/.norebuild

# Delete a number of static libraries that are not needed for any
# reason at runtime (and ideally should not be intalled at all if
# unnecessary)
#
# There are a few static libs that may need to be kept for re-building sagelib
# so we back them up first.
# (NOTE: It should never be necessary to re-build sagelib in the runtime
# environment, but currently this can happen when installing optional packages;
# see https://github.com/sagemath/sage-windows/issues/34)
SAVE_STATIC_LIBS="bliss braiding cliquer ratpoints rw symmetrica"

for libname in $SAVE_STATIC_LIBS; do
    # ignore any files that happen to be missing (e.g. some of these may be
    # optional packages)
    lib="local/lib/lib${libname}.a"
    if [ -f "$lib" ]; then
        mv "$lib" "${lib}.bak"
    fi
done

find "local/lib" \
    \( -type f -a -name '*.a' -a ! -name '*.dll.a' \) \
    -exec rm -f {} \;

for libname in $SAVE_STATIC_LIBS; do
    lib="local/lib/lib${libname}.a"
    if [ -f "${lib}.bak" ]; then
        mv "${lib}.bak" "$lib"
    fi
done

# Strip debug symbols from exes and dlls, saving hundreds of MB
find . -type f \( -name '*.exe' -o -name '*.dll' \) \
    -exec strip -g {} \;


# Move stupid, misnamed giac docs: the directory name ends with a space when it
# shouldn't, and InnoSetup has trouble with this
BROKEN_GIAC_DOC_DIR='local/share/doc/giac/fr '
if [ -d "$BROKEN_GIAC_DOC_DIR" ]; then
    mv "$BROKEN_GIAC_DOC_DIR" local/share/doc/giac/fr
fi
